package com.woniuxy.service.impl;

import com.woniuxy.mapper.AccountMapper;
import com.woniuxy.mapper.TranRecordMapper;
import com.woniuxy.pojo.Account;
import com.woniuxy.pojo.TranRecord;
import com.woniuxy.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.*;

@Service
@Transactional
public class AccountServiceImpl implements AccountService {
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private TranRecordMapper tranRecordMapper;

    /**
     *  spring事务中回滚机制
     *  默认情况下对于运行时异常是回滚的，对于检查异常是不会滚的，但是我们也可以通过重新指定来改变回滚策略
     *  rollbackFor=XX.class，指定XX类型的异常可以被回滚
     *  noRollbackFor=XX.class,指定XX类型的异常不会滚
     */
    @Transactional(timeout = 4,rollbackFor = FileNotFoundException.class,noRollbackFor = ArithmeticException.class)
    @Override
    public void transfer(String fromAccountno, String toAccountno, float money) throws IOException {
        /**
         * 转账的步骤
         * 1.查找对方的账户是否存在
         * 2.查询自己的账户
         */
        Account toAccount=accountMapper.selectAccountByAccountno(toAccountno);
        Account fromAccount=accountMapper.selectAccountByAccountno(fromAccountno);
        //转出指定的金额
        accountMapper.updateBalaneByAccount(fromAccountno,fromAccount.getBalance()-money);
        //此处模拟一个异常
        int i=10/0;
        //InputStream inputStream=new FileInputStream(new File("f:\\aa.txt"));
        //为了演示事务超时功能，这里模拟延迟5秒
        /*
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        */
        accountMapper.updateBalaneByAccount(toAccountno,toAccount.getBalance()+money);
        //转出者的动账记录
        TranRecord fromTranRecord=new TranRecord();
        fromTranRecord.setType(-1);
        fromTranRecord.setMoney(money);
        fromTranRecord.setMessage(fromAccountno+"转出"+money+"元");
        tranRecordMapper.addRecord(fromTranRecord);
        //转入者动账记录
        TranRecord toTranRecord=new TranRecord();
        toTranRecord.setType(1);
        toTranRecord.setMoney(money);
        toTranRecord.setMessage(toAccountno+"转入"+money+"元");
        tranRecordMapper.addRecord(toTranRecord);
    }
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    @Override
    public void addAccount(Account account) {
        this.accountMapper.addAccount(account);
    }
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void updateAccount(Account account) {
        this.accountMapper.updateAccount(account);
        //模拟一个异常
        int i=10/0;
    }
}





















